import math
import torch
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module


class GraphConvolution(Module):
    """
    Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
    """

    def __init__(self, in_features, out_features, bias=True):
        super(GraphConvolution, self).__init__()
        # 输入特征，每个输入样本的大小
        self.in_features = in_features

        # 输出特征，每个输出样本的大小
        self.out_features = out_features

        # 形状模块的可学习权重, in_features x out_features
        self.weight = Parameter(torch.FloatTensor(in_features, out_features))

        # 偏置，如果设置为False，则层将不会学习加法偏差; 默认值：True
        if bias:
            self.bias = Parameter(torch.FloatTensor(out_features))
        else:
            self.register_parameter('bias', None)

        # 参数随机初始化函数
        self.reset_parameters()

    def reset_parameters(self):
        # weight = [in_features, out_features]
        #  size(1)是指out_features, stdv=1/根号(out_features)
        stdv = 1. / math.sqrt(self.weight.size(1))

        # weight在区间(-stdv, stdv)之间均匀分布随机初始化
        self.weight.data.uniform_(-stdv, stdv)

        # bias均匀分布随机初始化
        if self.bias is not None:
            self.bias.data.uniform_(-stdv, stdv)

    def forward(self, input, adj):
        # 前向传播函数
        # AXW

        # input和self.weight矩阵相乘
        # XW
        support = torch.mm(input, self.weight)

        # spmm()是稀疏矩阵乘法，减小运算复杂度
        # AXW
        output = torch.spmm(adj, support)

        if self.bias is not None:
            # 返回: 系数*输入*权重 + 偏置
            return output + self.bias
        else:
            # 返回: 系数*输入*权重, 无偏置
            return output

    def __repr__(self):
        # 打印形式是：GraphConvolution (输入特征 -> 输出特征)
        return self.__class__.__name__ + ' (' \
               + str(self.in_features) + ' -> ' \
               + str(self.out_features) + ')'
